
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="第二十二章 Django ORM-多表实例">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>第二十二章 Django ORM-多表实例 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        第二十二章 Django ORM-多表实例
      </h1>
      <span>
        
        <time class="time" datetime="2019-09-28T16:00:00.000Z">
        2019-09-29
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h2 id="第二十二章-Django-ORM-–-多表实例"><a href="#第二十二章-Django-ORM-–-多表实例" class="headerlink" title="第二十二章 Django ORM – 多表实例"></a>第二十二章 Django ORM – 多表实例</h2><h4 id="表与表之间的关系可分为以下三种："><a href="#表与表之间的关系可分为以下三种：" class="headerlink" title="表与表之间的关系可分为以下三种："></a>表与表之间的关系可分为以下三种：</h4><ul>
<li>一对一: 一个人对应一个身份证号码，数据字段设置 unique。</li>
<li>一对多: 一个家庭有多个人，一般通过外键来实现。</li>
<li>多对多: 一个学生有多门课程，一个课程有很多学生，一般通过第三个表来实现关联。</li>
</ul>
<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/orm11.png" alt="aaa"></p>
<h4 id="创建模型"><a href="#创建模型" class="headerlink" title="创建模型"></a>创建模型</h4><p>接下来我们来看下多表多实例。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    title = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    price = models.DecimalField(max_digits=<span class="number">5</span>, decimal_places=<span class="number">2</span>)</span><br><span class="line">    pub_date = models.DateField()</span><br><span class="line">    publish = models.ForeignKey(<span class="string">"Publish"</span>, on_delete=models.CASCADE)</span><br><span class="line">    m = models.ManyToManyField(<span class="string">"Author"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Publish</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    city = models.CharField(max_length=<span class="number">64</span>)</span><br><span class="line">    email = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    age = models.SmallIntegerField()</span><br><span class="line">    au_detail = models.OneToOneField(<span class="string">"AuthorDetail"</span>, on_delete=models.CASCADE)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorDetail</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    gender_choices = (</span><br><span class="line">        (<span class="number">0</span>, <span class="string">"女"</span>),</span><br><span class="line">        (<span class="number">1</span>, <span class="string">"男"</span>),</span><br><span class="line">        (<span class="number">2</span>, <span class="string">"保密"</span>),</span><br><span class="line">    )</span><br><span class="line">    gender = models.SmallIntegerField(choices=gender_choices)</span><br><span class="line">    tel = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    addr = models.CharField(max_length=<span class="number">64</span>)</span><br><span class="line">    birthday = models.DateField()</span><br></pre></td></tr></table></figure>

<p>说明：</p>
<p>1、EmailField 数据类型是邮箱格式，底层继承 CharField，进行了封装，相当于 MySQL 中的 varchar。<br>2、Django1.1 版本不需要联级删除：on_delete=models.CASCADE，Django2.2 需要。<br>3、一般不需要设置联级更新.<br>4、外键在一对多的多中设置：models.ForeignKey(“关联类名”, on_delete=models.CASCADE)。<br>5、OneToOneField = ForeignKey(…，unique=True)设置一对一。<br>6、若有模型类存在外键，创建数据时，要先创建外键关联的模型类的数据，不然创建包含外键的模型类的数据时，外键的关联模型类的数据会找不到。</p>
<h4 id="表结构"><a href="#表结构" class="headerlink" title="表结构"></a>表结构</h4><p>书籍表 Book：title 、 price 、 pub_date 、 publish（外键，多对一） 、 authors（多对多）</p>
<p>出版社表 Publish：name 、 city 、 email</p>
<p>作者表 Author：name 、 age 、 au_detail（一对一）</p>
<p>作者详情表 AuthorDetail：gender 、 tel 、 addr 、 birthday</p>
<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-orm2_1.png" alt="111"></p>
<h4 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h4><p>我们在 MySQL 中执行以下 SQL 插入操作：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">insert into app01_publish(name,city,email) values (<span class="string">"华山出版社"</span>, <span class="string">"华山"</span>, <span class="string">"hs@163.com"</span>), (<span class="string">"明教出版社"</span>, <span class="string">"黑木崖"</span>, <span class="string">"mj@163.com"</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 先插入 authordetail 表中多数据</span></span><br><span class="line">insert into app01_authordetail(gender,tel,addr,birthday) values (<span class="number">1</span>,<span class="number">13432335433</span>,<span class="string">"华山"</span>,<span class="string">"1994-5-23"</span>), (<span class="number">1</span>,<span class="number">13943454554</span>,<span class="string">"黑木崖"</span>,<span class="string">"1961-8-13"</span>), (<span class="number">0</span>,<span class="number">13878934322</span>,<span class="string">"黑木崖"</span>,<span class="string">"1996-5-20"</span>) </span><br><span class="line"></span><br><span class="line"><span class="comment"># 再将数据插入 author，这样 author 才能找到 authordetail </span></span><br><span class="line">insert into app01_author(name,age,au_detail_id) values (<span class="string">"令狐冲"</span>,<span class="number">25</span>,<span class="number">1</span>), (<span class="string">"任我行"</span>,<span class="number">58</span>,<span class="number">2</span>), (<span class="string">"任盈盈"</span>,<span class="number">23</span>,<span class="number">3</span>)</span><br></pre></td></tr></table></figure>

<h3 id="ORM-添加数据"><a href="#ORM-添加数据" class="headerlink" title="ORM - 添加数据"></a>ORM - 添加数据</h3><h4 id="一对多-外键-ForeignKey"><a href="#一对多-外键-ForeignKey" class="headerlink" title="一对多(外键 ForeignKey)"></a>一对多(外键 ForeignKey)</h4><h5 id="1-增加数据"><a href="#1-增加数据" class="headerlink" title="1.增加数据"></a>1.增加数据</h5><h6 id="方式一-传对象的形式，返回值的数据类型是对象，书籍对象。"><a href="#方式一-传对象的形式，返回值的数据类型是对象，书籍对象。" class="headerlink" title="方式一: 传对象的形式，返回值的数据类型是对象，书籍对象。"></a>方式一: 传对象的形式，返回值的数据类型是对象，书籍对象。</h6><p>步骤：<br>a. 获取出版社对象<br>b. 给书籍的出版社属性 pulish 传出版社对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_book</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment">#  获取出版社对象</span></span><br><span class="line">    pub_obj = models.Publish.objects.filter(id=<span class="number">1</span>).first()</span><br><span class="line">    <span class="comment">#  给书籍的出版社属性publish传出版社对象</span></span><br><span class="line">    book = models.Book.objects.create(title=<span class="string">"51aiops教程"</span>, price=<span class="number">200</span>, pub_date=<span class="string">"2010-10-10"</span>, publish=pub_obj)</span><br><span class="line">    print(book, type(book))</span><br></pre></td></tr></table></figure>

<h6 id="方式二-传对象-id-的形式-由于传过来的数据一般是-id-所以传对象-id-是常用的-。"><a href="#方式二-传对象-id-的形式-由于传过来的数据一般是-id-所以传对象-id-是常用的-。" class="headerlink" title="方式二: 传对象 id 的形式(由于传过来的数据一般是 id,所以传对象 id 是常用的)。"></a>方式二: 传对象 id 的形式(由于传过来的数据一般是 id,所以传对象 id 是常用的)。</h6><p>一对多中，设置外键属性的类(多的表)中，MySQL 中显示的字段名是:外键属性名_id。</p>
<p>返回值的数据类型是对象，书籍对象。</p>
<p>步骤：</p>
<p>a. 获取出版社对象的 id<br>b. 给书籍的关联出版社字段 pulish_id 传出版社对象的 id</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_book</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment">#  获取出版社对象</span></span><br><span class="line">    pub_obj = models.Publish.objects.filter(id=<span class="number">1</span>).first()</span><br><span class="line">    <span class="comment">#  获取出版社对象的id</span></span><br><span class="line">    id = pub_obj.id</span><br><span class="line">    <span class="comment">#  给书籍的关联出版社字段 publish_id 传出版社对象的id</span></span><br><span class="line">    book = models.Book.objects.create(title=<span class="string">"冲灵剑法"</span>, price=<span class="number">100</span>, pub_date=<span class="string">"2004-04-04"</span>, publish_id=id)</span><br><span class="line">    print(book, type(book))</span><br></pre></td></tr></table></figure>

<h5 id="2-查询数据"><a href="#2-查询数据" class="headerlink" title="2.查询数据"></a>2.查询数据</h5><blockquote>
<p>正向：属性名称<br>反向：小写类名_set</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### 1.查询主键为 1 的书籍的出版社所在的城市（正向）。</span></span><br><span class="line">book = models.Book.objects.filter(id=<span class="number">1</span>).first()</span><br><span class="line">res = book.publish.city</span><br><span class="line">print(res, type(res))</span><br><span class="line"></span><br><span class="line"><span class="comment">### 2.查询明教出版社出版的书籍名（反向）。</span></span><br><span class="line"><span class="comment">### 反向：对象.小写类名_set(pub.book_set) 可以跳转到关联的表(书籍表)。</span></span><br><span class="line"><span class="comment">### pub.book_set.all()：取出书籍表的所有书籍对象，在一个 QuerySet 里，遍历取出一个个书籍对象。</span></span><br><span class="line"></span><br><span class="line">pub = models.Publish.objects.filter(name=<span class="string">"明教出版社"</span>).first()</span><br><span class="line">res = pub.book_set.all()</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> res:</span><br><span class="line">    print(i.title)</span><br></pre></td></tr></table></figure>

<h5 id="3-基于双下划线的跨表查询"><a href="#3-基于双下划线的跨表查询" class="headerlink" title="3.基于双下划线的跨表查询"></a>3.基于双下划线的跨表查询</h5><blockquote>
<p>正向：属性名称<strong>跨表的属性名称<br>反向：小写类名</strong>跨表的属性名称</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">### 查询明教出版社出版过的所有书籍的名字与价格</span></span><br><span class="line">res = models.Book.objects.filter(publish__name=<span class="string">"明教出版社"</span>).values_list(<span class="string">"title"</span>, <span class="string">"price"</span>)</span><br></pre></td></tr></table></figure>

<p><strong>反向：通过 小写类名<strong>跨表的属性名称（book</strong>title，book__price） 跨表获取数据。</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">res = models.Publish.objects.filter(name=<span class="string">"明教出版社"</span>).values_list(<span class="string">"book__title"</span>,<span class="string">"book__price"</span>)</span><br></pre></td></tr></table></figure>

<h5 id="4-删除数据"><a href="#4-删除数据" class="headerlink" title="4.删除数据"></a>4.删除数据</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">on_delete=models.CASCADE, <span class="comment"># 删除关联数据,与之关联也删除</span></span><br><span class="line">on_delete=models.DO_NOTHING, <span class="comment"># 删除关联数据,什么也不做,会报IntegrityError错</span></span><br><span class="line">on_delete=models.PROTECT, <span class="comment"># 删除关联数据,引发错误ProtectedError</span></span><br><span class="line"><span class="comment"># models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True)</span></span><br><span class="line">on_delete=models.SET_NULL, <span class="comment"># 删除关联数据,与之关联的值设置为null（前提FK字段需要设置为可空,一对一同理）</span></span><br><span class="line"><span class="comment"># models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值')</span></span><br><span class="line">on_delete=models.SET_DEFAULT, <span class="comment"># 删除关联数据,与之关联的值设置为默认值（前提FK字段需要设置默认值,一对一同理）</span></span><br></pre></td></tr></table></figure>

<h4 id="多对多-ManyToManyField-：在第三张关系表中新增数据"><a href="#多对多-ManyToManyField-：在第三张关系表中新增数据" class="headerlink" title="多对多(ManyToManyField)：在第三张关系表中新增数据"></a>多对多(ManyToManyField)：在第三张关系表中新增数据</h4><h5 id="1-新增数据"><a href="#1-新增数据" class="headerlink" title="1.新增数据"></a>1.新增数据</h5><p>我们除了可以手动的在数据库中添加数据外，还可以使用如下代码添加数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 增加</span></span><br><span class="line">    obj = models.Author.objects.get(id=<span class="number">1</span>)</span><br><span class="line">    obj.m.add(<span class="number">5</span>)</span><br><span class="line">    obj.m.add(<span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">    obj.m.add(*[<span class="number">4</span>, <span class="number">5</span>])</span><br></pre></td></tr></table></figure>

<h5 id="2-查询数据-1"><a href="#2-查询数据-1" class="headerlink" title="2.查询数据"></a>2.查询数据</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment"># 正向查找，获取 Book id 为1 的作者</span></span><br><span class="line">    obj = models.Book.objects.get(id=<span class="number">1</span>)</span><br><span class="line">    l = obj.m.all()</span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> l:</span><br><span class="line">        print(item.id, item.name)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 反向查找，获取 著作为 1 的作者</span></span><br><span class="line">    obj = models.Author.objects.get(id=<span class="number">1</span>)</span><br><span class="line">    m = obj.book_set.all()</span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> m:</span><br><span class="line">        print(item.id, item.name)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">'ok'</span>)</span><br></pre></td></tr></table></figure>

<h5 id="3-删除数据和修改数据"><a href="#3-删除数据和修改数据" class="headerlink" title="3.删除数据和修改数据"></a>3.删除数据和修改数据</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 删除</span></span><br><span class="line">    obj.m.remove(<span class="number">5</span>)</span><br><span class="line">    obj.m.remove(<span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">    obj.m.remove(*[<span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 清空</span></span><br><span class="line">    obj.m.clear()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 更新</span></span><br><span class="line">    obj.m.set([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br></pre></td></tr></table></figure>

<h4 id="一对一"><a href="#一对一" class="headerlink" title="一对一"></a>一对一</h4><h5 id="1-新增数据-1"><a href="#1-新增数据-1" class="headerlink" title="1.新增数据"></a>1.新增数据</h5><p><strong>跟之前给普通表新增数据都是一样，同一对多的新增数据</strong></p>
<h5 id="2-查询数据-2"><a href="#2-查询数据-2" class="headerlink" title="2.查询数据"></a>2.查询数据</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">查询令狐冲的电话（正向）</span><br><span class="line"></span><br><span class="line">正向：对象.属性 (author.au_detail) 可以跳转到关联的表(作者详情表)</span><br><span class="line"></span><br><span class="line">author = models.Author.objects.filter(name=<span class="string">"令狐冲"</span>).first()</span><br><span class="line">res = author.au_detail.tel</span><br><span class="line">print(res, type(res))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">查询所有住址在黑木崖的作者的姓名（反向）。</span><br><span class="line"></span><br><span class="line">一对一的反向，用 对象.小写类名 即可，不用加 _set。</span><br><span class="line"></span><br><span class="line">反向：对象.小写类名(addr.author)可以跳转到关联的表(作者表)。</span><br><span class="line"></span><br><span class="line">addr = models.AuthorDetail.objects.filter(addr=<span class="string">"黑木崖"</span>).first()</span><br><span class="line">res = addr.author.name</span><br><span class="line">print(res, type(res))</span><br></pre></td></tr></table></figure>

<h5 id="3-基于双下划线的跨表查询-1"><a href="#3-基于双下划线的跨表查询-1" class="headerlink" title="3.基于双下划线的跨表查询"></a>3.基于双下划线的跨表查询</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">查询任我行的手机号。</span><br><span class="line"></span><br><span class="line">正向：通过 属性名称__跨表的属性名称(au_detail__tel) 跨表获取数据。</span><br><span class="line"></span><br><span class="line">res = models.Author.objects.filter(name=<span class="string">"任我行"</span>).values_list(<span class="string">"au_detail__tel"</span>)</span><br></pre></td></tr></table></figure>


    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#第二十二章-Django-ORM-–-多表实例"><span class="toc-text">第二十二章 Django ORM – 多表实例</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#表与表之间的关系可分为以下三种："><span class="toc-text">表与表之间的关系可分为以下三种：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#创建模型"><span class="toc-text">创建模型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#表结构"><span class="toc-text">表结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#插入数据"><span class="toc-text">插入数据</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ORM-添加数据"><span class="toc-text">ORM - 添加数据</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#一对多-外键-ForeignKey"><span class="toc-text">一对多(外键 ForeignKey)</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-增加数据"><span class="toc-text">1.增加数据</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#方式一-传对象的形式，返回值的数据类型是对象，书籍对象。"><span class="toc-text">方式一: 传对象的形式，返回值的数据类型是对象，书籍对象。</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#方式二-传对象-id-的形式-由于传过来的数据一般是-id-所以传对象-id-是常用的-。"><span class="toc-text">方式二: 传对象 id 的形式(由于传过来的数据一般是 id,所以传对象 id 是常用的)。</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-查询数据"><span class="toc-text">2.查询数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-基于双下划线的跨表查询"><span class="toc-text">3.基于双下划线的跨表查询</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4-删除数据"><span class="toc-text">4.删除数据</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#多对多-ManyToManyField-：在第三张关系表中新增数据"><span class="toc-text">多对多(ManyToManyField)：在第三张关系表中新增数据</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-新增数据"><span class="toc-text">1.新增数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-查询数据-1"><span class="toc-text">2.查询数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-删除数据和修改数据"><span class="toc-text">3.删除数据和修改数据</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#一对一"><span class="toc-text">一对一</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-新增数据-1"><span class="toc-text">1.新增数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-查询数据-2"><span class="toc-text">2.查询数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-基于双下划线的跨表查询-1"><span class="toc-text">3.基于双下划线的跨表查询</span></a></li></ol></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2019/09/02/MVC和MTV的介绍/" rel="next" title="MVC和MTV的模型">
          MVC和MTV的模型
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2019/09/29/DjangoOrm模型的使用/" rel="prev" title="第二十一章 Django的模型">
            第二十一章 Django的模型
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
